/* eslint-disable */
import axios from 'axios'
import { ElMessage as Message } from 'element-plus'
import { SessionStorage } from './storage'
import constant from './constant'
// import { i18n } from '@/i18n/index'
const request = axios.create({
  baseURL: '',
  timeout: 1000 * 60 * 5
})
// 请求拦截
request.interceptors.request.use(
  (config) => {
    var sessionToken = SessionStorage.getItem(constant.sessionStorageUserKey)
    var token = sessionToken && sessionToken.token
    if (token) {
      config.headers['Authorization'] = token
    } else {
      config.headers['Authorization'] = null
    }
    // config.headers['accept'] = 'application/json'
    return config
  },
  function (error) {
    console.log('error', error)
    return Promise.reject(error)
  }
)
// 响应拦截
// 响应拦截器
request.interceptors.response.use(
  (res) => {
    const responseBody = res.data
    if (!responseBody.success) {
      if (responseBody.message) {
        Message.error(responseBody.message)
      }
      try {
        Promise.reject(responseBody)
      } finally {
        return res
      }
    }
    return responseBody
  },
  (error) => {
    const errorResponse = error.response
    const errorBody = errorResponse.data

    if (errorBody && !errorBody.success) {
      if (errorBody.message) {
        Message.error(errorBody.message)
      }
    } else {
      Message.error(errorBody)
    }

    if (errorBody && errorBody.code) {
      if (errorBody.code === 10006) {
        if (!isRelogin.show) {
          isRelogin.show = true
          MessageBox.confirm('登录状态已过期，您可以继续留在该页面，或者重新登录', '系统提示', {
            confirmButtonText: '重新登录',
            // cancelButtonText: '取消',
            type: 'warning'
          })
            .then(() => {
              window.location.href = window.origin
            })
            .catch(() => {})
            .finally(() => {
              isRelogin.show = false
            })
        }
      }
      if (errorBody.code === 10013) {
        window.location.href = window.origin
      }
    }

    return Promise.reject(error)
  }
)

export default request
